from werkzeug.security import check_password_hash
from wtforms import PasswordField
from wtforms.validators import ValidationError, Length, DataRequired, EqualTo
from flask_jwt_extended import get_jwt_identity, verify_jwt_in_request
from app.form.base_form import BaseForm
from app.models import BlogUser


class ChangePasswordForm(BaseForm):
    """修改密码校验
    """
    password_old = PasswordField(validators=[
        DataRequired('旧密码不能为空'),
        Length(6, 32, message="密码长度6~32个字符")
    ])
    password = PasswordField(validators=[
        DataRequired('新密码不允许为空'),
        Length(6, 32, message="密码长度6~32个字符")
    ])
    password_confirm = PasswordField(validators=[
        DataRequired('确认密码不允许为空'),
        Length(6, 32, message="密码长度6~32个字符"),
        EqualTo("password", message="新密码和确认密码不一致")
    ])

    # 旧密码验证
    def validate_password_old(self, field):
        user_id = get_jwt_identity()
        if not user_id:
            raise ValidationError(message="用户凭证无法获取")
        user = BlogUser.query.get(user_id)
        if not user:
            raise ValidationError(message="登录用户找不到")
        if not check_password_hash(user.password, field.data):
            raise ValidationError(message="密码不正确")
